/**
 * @file field
 * @author fanxueliang@qq.com
 */
import {map, isEmpty, isNil} from 'lodash-es';
import type {
    EnumSpecItem,
    FieldDatasource,
    SelectStringField,
    EnumValuesSpecItem,
    ExtensionsAttr,
    ExpressionProps
} from '../interface';
import {getBasicField} from '../util';

export function createEnumField(spec: EnumSpecItem, showIndex: number, path: string) {
    let component = 'EnumSelect';
    if (spec.ui) {
        component = spec.ui;
    }
    const enumValues = spec.enumValues || [];
    const datasource = map<EnumValuesSpecItem, FieldDatasource>(enumValues, (enumItem) => {
        let hidden: string | ExpressionProps[] | null = null;
        if (enumItem[':hidden']) {
            hidden = enumItem[':hidden'];
        } else if (enumItem.hiddenExpression && enumItem.hiddenExpression.length) {
            hidden = enumItem.hiddenExpression.map((v) => JSON.parse(v));
        }
        const result = {
            label: enumItem.displayName,
            value: enumItem.value
        } as FieldDatasource;
        if (hidden) {
            result.hidden = hidden;
        }
        return result;
    });
    const basicField = getBasicField(spec, path, showIndex);
    const {
        api = null,
        payload = null,
        useSource = null,
        searchable = null,
        trigger = 'search'
    } = spec.extraAttr ? spec.extraAttr.remote || {} : {};
    const extensions: ExtensionsAttr[] = [];
    if (spec?.extraAttr?.extensions) {
        extensions.push(...spec.extraAttr.extensions);
    }
    if (api || !isEmpty(useSource)) {
        extensions.push({
            name: 'manualVerification'
        });
    }

    return {
        ...basicField,
        extensions,
        isLeaf: true,
        type: 'STRING',
        spec,
        component,
        datasource,
        api,
        searchable: isNil(searchable) ? !!api : searchable,
        payload,
        useSource,
        trigger
    } as SelectStringField;
}
